<css href="/Public/design/css/style.css?v=4,/Public/design/iconfont/iconfont.css" />
<js href="/Public/Sortable/Sortable.js" />
<style>
    #form-box {
        font-size: 12px;
    }
    
    #form-box .layui-form-label {
        width: 60px;
        padding: 9px 10px;
    }
    
    #form-box .layui-input-block {
        margin-left: 80px;
    }
    
    .component-title {
        text-align: center;
        line-height: 60px;
        font-size: 24px;
    }
    
    #form-box select {
        line-height: 36px;
        height: 36px;
        padding: 0 15px;
        color: #666;
        border-color: #ddd;
        border-radius: 3px;
    }
    .hhq-comp{
        position: relative;
    }
    .hhq-comp-title{
        padding:0 30px;
        line-height: 40px;
        font-size: 16px;
        background-color: darkolivegreen;
        color:#fff;
    }
    .hhq-comp-box{
        font-size:14px;
        padding:10px;
        line-height: 30px;
        width:calc(100% - 20px);
        /* background-color: #666; */
        /* white-space: normal; */
        white-space: nowrap;
        text-overflow: ellipsis; 
        overflow: hidden; 
    }
    .design-main .component-box{
        text-align: center;
        background-color: #2C65DE;
        color:#fff;
    }
    .design-right .layui-form-label{
        white-space: pre-line;
    }
    
    /* 自定义下拉框容器 */
    .select-multiple {
        height:auto !important;
        padding: 8px !important;
        /* border: 2px solid #4CAF50; */
        /* border-radius: 6px; */
        /* background-color: #f8f8f8; */
        /* font-family: Arial, sans-serif; */
        /* font-size: 14px; */
        background-image:none !important;
    }

    /* 下拉选项样式 */
    .select-multiple option {
        padding: 10px;
        /* margin: 2px 0; */
        background-color: white;
        transition: background-color 0.3s;
    }

    /* 鼠标悬停效果 */
    /* .select-multiple option:hover {
        background-color: #e0f7fa !important;
    } */

    /* 选中项高亮 */
    .select-multiple option:checked {
        /* background-color: #4CAF50;
        color: white; */
    }

    /* 隐藏原生下拉箭头 */
    .select-multiple {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
    }

    /* 自定义滚动条 */
    /* .select-multiple::-webkit-scrollbar {
        width: 8px;
    }
    .select-multiple::-webkit-scrollbar-thumb {
        background: #4CAF50;
        border-radius: 4px;
    } */
</style>
<div class="design-box">
    <div class="design-left">
        <div class="layui-card nav" style="height:calc(100% - 30px);">
            <div class="layui-card-header">组件</div>
            <div class="layui-card-body components-draggable" id="components"></div>
            <div class="layui-clear"></div>
        </div>
    </div>
    <div class="design-center">
        <div class="layui-card content design-main-box">
            <div class="layui-card-header">地图设计
                <button class="layui-btn layui-btn-sm layui-btn-danger del-form" data-type="del"> <i class="layui-icon"></i></button>
            </div>
            <div class="layui-card-body code">
                <div class="design-main" id="design-main">
                </div>
            </div>
        </div>
    </div>

    <div class="design-right">
        <div class="layui-card r-code-html" style="height:calc(100% - 30px);">
            <div class="layui-card-header">参数设置</div>
            <div class="layui-card-body">
                <form action="" onsubmit="return false;" class="layui-form hhq-form" id="form-box">
                </form>
            </div>
        </div>
    </div>
</div>

<div class="layui-footer layui-form-footer">
    <form class="layui-form hhq-form">
        <a href="javascript:parent.think_close();" class="layui-btn layui-btn-primary"  type="button" sa-event="closeDialog">取消</a>
        <button class="layui-btn" lay-filter="submitIframe" type="button" lay-submit="" id="submit">提交</button>
        <div class="layui-input-inline">
            <input type="number" id="read-stage-id" placeholder="关卡ID" class="layui-input">
        </div>
        <button class="layui-btn layui-btn-normal" lay-filter="generateIframe" type="button" lay-submit="" id="read-config">读取数据</button>
        <button class="layui-btn layui-btn-normal" lay-filter="saveIframe" type="button" lay-submit="" id="save-config">保存数据</button>
        <button class="layui-btn layui-btn-normal" lay-filter="generateIframe" type="button" lay-submit="" id="generate-config">生成正式文件</button>
        <button class="layui-btn layui-btn-normal" lay-filter="generateIframe" type="button" lay-submit="" data-type="trial" id="generate-trial-config">生成抢鲜文件</button>

    </form>
    
</div>

<script id="componentsTpl" type="text/html">
    {{# layui.each(d, function(index, item){ }}
    <div class="component" data-key="{{item.key}}">
        <div class="component-box">
            <span class="iconfont {{item.icon}}"></span>
            <div class="component-name">{{item.name}}</div>
        </div>
    </div>
    {{# }); }}
</script>
<div id="tpls"></div>

<script id="formTpl" type="text/html">
    {{# layui.each(d, function(index, item){ }}
    <div class="layui-form-item">
        <label class="layui-form-label">{{item.name}}</label>
        <div class="layui-input-block">
            {{# if(item.type == 'text'){ }}
            <input type="text" name="{{item.key}}" required lay-verify="required" placeholder="请输入{{item.name}}" autocomplete="off" class="layui-input"> 
            {{# }else if(item.type == 'textarea'){ }}
            <textarea name="{{item.key}}" rows="12FGVAXDRfaR" placeholder="请输入{{item.name}}" class="layui-textarea"></textarea> 
            {{# }else if(item.type == 'select'){ }} 
                <select name="{{item.key}}" class="layui-select">
                    {{# for(var i = 0 ; i < item.options.length ; i++){ }} 
                        <option value="{{item.options[i][0]}}" >{{item.options[i][1]}}</option> 
                    {{# } }} 
                </select>
            {{# }else if(item.type == 'select-m'){ }}
                <select class="select-multiple" name="{{item.key}}" multiple size="{{item.options.length}}" lay-ignore>
                    {{# for(var i = 0 ; i < item.options.length ; i++){ }}
                        <option value="{{item.options[i][0]}}">{{item.options[i][1]}}</option>
                    {{# } }}
                </select>
            {{# } }}
        </div>
    </div>
    {{# }); }}
</script>

<js href="/Public/store.everything.min.js" />
<script>
    // store.set('user', { name:'Marcus' })
    // store.get('user')
    // store.remove('user')
    // store.clearAll()
    // store.each(function(value, key) {
    //     console.log(key, '==', value)
    // })
    var SAVE_NANE = 'designSaveData';
    var saveData = typeof(store.get(SAVE_NANE)) == 'undefined' ? {} : store.get(SAVE_NANE); //最终存储的数据
    layui.use(['element', 'laytpl', 'think', 'form'], function() {
        var element = layui.element,
            laytpl = layui.laytpl,
            form = layui.form;

        //读取数据
        $('#read-config').click(function() {
            $stage_id = $('#read-stage-id').val();
            if(!$stage_id){
                layer.msg('请输入关卡ID');
                return false; 
            }
            $.ajax({
                url: '/Game/Admin/config_read',
                type: 'post',
                data: {
                    stage_id: $stage_id
                },
                success: function(ret) {
                    console.log('ret');
                    console.log(ret);
                    if (!ret.status) {
                        layer.msg(ret.info);
                        return false; 
                    }
                    layer.msg(ret.info)
                    let data = ret.data.config_data;
                    console.log(data);
                    store.set(SAVE_NANE, data);
                    window.location.reload();
                } 
            })
        })

        //保存数据
        $('#save-config').click(function() {
            var data = [];
            var i = 0;
            console.log(saveData);
            let stageId = null;
            for (key in saveData) {
                if(saveData[key].component == 'baseConfig'){
                    stageId = saveData[key].stageId;
                    break;
                }
            }
            if(!stageId){
                layer.msg('请输入关卡ID'); 
            }
            $.ajax({
                url: '/game/Admin/config_save',
                type: 'post',
                data: {
                    stage_id: stageId,
                    config_data: json_to_str(saveData)
                },
                success: function(ret) {
                    layer.msg(ret.info)
                } 
            })
        })

        //生成配置文件
        $('#generate-config, #generate-trial-config').click(function() {
            console.log('generate');
            // var dataJson = json_to_str(saveData);
            // layer.alert(dataJson);
            // 剔除掉没有数据的
            var data = [];
            var i = 0;
            console.log(saveData);
            for (key in saveData) {
                var d = saveData[key];
                data[i++] = d;
            }
            data = json_to_str(data);
            $.ajax({
                url: '/game/Admin/config_generate',
                type: 'post',
                data: {
                    data: data,
                    is_trial: $(this).attr('data-type')
                },
                success: function(ret) {
                    if (ret.status) {
                        layer.msg(ret.info, {
                            icon: 1,
                            time: 1000 
                        })
                    } 
                } 
            })
        });
        //监听提交
        $('#submit').click(function() {
            // var dataJson = json_to_str(saveData);
            // layer.alert(dataJson);
            // 剔除掉没有数据的
            var data = [];
            var i = 0;
            for (key in saveData) {
                var d = saveData[key];
                data[i++] = d;
            }
            layer.alert(json_to_str(data));
        });

        var components = {};
        $.get('/game/api_admin/get_module_all', function(ret) {
            console.log(ret);
            if (ret.status) {
                for (var i = 0; i < ret.data.length; i++) {
                    var tmp = ret.data[i];
                    components[tmp['key']] = tmp;
                    var html = '<script id="' + tmp['key'] + 'Tpl" type="text/html"> ' + tmp['tpl'] + ' </scri' + 'pt>';
                    $('#tpls').append(html);
                }

                laytpl($('#componentsTpl').html()).render(ret.data, function(html) {
                    $('#components').html(html);
                    //拖拽监听
                    $('.components-draggable').each(function() {
                        var _this = this;
                        new Sortable(_this, {
                            group: {
                                name: 'design',
                                pull: 'clone', //克隆本区域元素到其他区域
                                put: false, //禁止本区域实现拖动或拖入
                            },
                            ghostClass: "ghost",
                            sort: false,
                            animation: 150,
                            onClone: function(evt) {
                                // console.log(evt.clone);

                            },
                            onEnd: function(evt) {
                                // console.log('onEnd.foo:', [evt.item, evt.from]);
                                // console.log(evt.oldIndex);
                                // console.log(evt.newIndex);
                                // var itemEl = evt.item;
                                // console.log(itemEl);
                                // console.log("onEnd");
                            }
                        });
                    });
                });
                init_desing_main(); //在这里初始化
            }
        });

        listen_action_click();
        //统一的监听事件
        function listen_action_click() {
            $('#design-main .component').unbind('click').click(function() {
                if (!$(this).hasClass('active')) {
                    $('.component.active').removeClass('active');
                    $(this).addClass('active');
                }
                render_form(); //渲染表单
            });
            //删除组件
            $('.component .layui-icon-delete').unbind('click').click(function() {
                var $dom = $(this).parent('.widget-view-action').parent('.component');
                var domIndex = $dom.index();
                var id = $('#design-main .component.active').find('.component-item').attr('id');
                delete saveData[id];
                store.set(SAVE_NANE, saveData); //存储起来
                // console.log(domIndex);
                $dom.remove(); //删除元素
                if ($('#design-main .component').length) {
                    $('#design-main .component').eq(domIndex - 1 >= 0 ? domIndex - 1 : 0).addClass('active');
                    render_form(); //渲染表单
                }
            });
            render_form(); //渲染表单
        }

        /**
         * 渲染表单
         */
        function render_form() {
            var $dom = $('#design-main').find(".component.active"); //获取当前选中的dom
            if (typeof(components[$dom.data('key')]) == 'undefined') {
                return;
            }
            var jsonForm = str_to_json(components[$dom.data('key')]['json']);
            console.log(jsonForm['fields']);
            laytpl($('#formTpl').html()).render(jsonForm['fields'], function(html) {
                // console.log(html);
                $('#form-box').html(html);
                form.render();
                update_save_data();
                render_form_data();
            });
        }

        /**
         * 渲染表单数据
         */
        function render_form_data() {
            var id = $('#design-main .component.active').find('.component-item').attr('id');
            var data = saveData[id];
            $('#form-box :input').each(function() {
                var _this = $(this);
                var tag = _this.prop('tagName');
                var name = $(this).attr('name');
                if (tag == 'INPUT' || tag == 'TEXTAREA' || tag == 'SELECT') {
                    _this.val(data[name]);
                }
            });
            form.render()
        }

        // 更新存储数据
        function update_save_data() {
            let id = $('#design-main .component.active').find('.component-item').attr('id');
            form.on('select', function(e){
                store_save_data(id, e.elem.name, e.elem.value);
            })
            form.on('checkbox', function(e){
                store_save_data(id, e.elem.name, e.elem.value);
            })
            form.on('radio', function(e){
                store_save_data(id, e.elem.name, e.elem.value);
            })
            form.on('switch', function(e){
                store_save_data(id, e.elem.name, e.elem.value);
            })
            $('#form-box :input').bind('input propertychange', function() {
                store_save_data(id, $(this).attr('name'), $(this).val());
            });
        }

        function store_save_data(id, key, value){
            saveData[id][key] = value
            store.set(SAVE_NANE, saveData); //存储起来
            //在这里处理预览的显示
            $('#'+id).find('.hhq-comp-box').html(JSON.stringify(saveData[id]));
        }

        function init_desing_main() {
            // 初始化数据
            for (key in saveData) {
                var d = saveData[key];
                var htmlBegin = '<div class="component" data-key="' + d['component'] + '"><div class="widget-view-action"><i class="layui-icon layui-icon-delete"></i></div><div class="widget-view-drag"><i class="layui-icon layui-icon-screen-full"></i></div><div class="component-cnt">';
                var htmlEnd = '</div></div>';
                laytpl($('#' + d['component'] + 'Tpl').html()).render({
                    id: key
                }, function(html) {
                    $('#design-main').append(htmlBegin + html + htmlEnd);
                    var text = JSON.stringify(d);
                    $('#' + key).find('.hhq-comp-box').html(text);
                });
            }

            $('#design-main .component').eq(0).addClass('active');
            render_form();
            listen_action_click();

            new Sortable.create(document.getElementById("design-main"), {
                group: {
                    name: 'design'
                },
                handle: '.widget-view-drag',
                ghostClass: "ghost",
                animation: 200,
                onAdd: function(evt) {
                    evt.item.innerHTML = '<div class="widget-view-action"><i class="layui-icon layui-icon-delete"></i></div>' +
                        '<div class="widget-view-drag"><i class="layui-icon layui-icon-screen-full"></i></div>' +
                        '<div class="component-cnt"></div>';
                    // console.log(options);
                    // evt.item.innerHTML = $('#componentTpl').html();
                    $('.component.active').removeClass('active');
                    $(evt.item).addClass('active');
                    var componentKey = $(evt.item).data('key');
                    // console.log(componentKey);
                    var componentConfig = components[componentKey]; //配置数据
                    componentConfig.id = guid();
                    // console.log(componentConfig);
                    var componentTpl = $('#' + componentKey + 'Tpl').html(); //配置模版
                    var $dom = $(evt.item).find('.component-cnt');
                    laytpl(componentTpl).render(componentConfig, function(html) {
                        $dom.html(html);
                        //添加数据
                        var jsonForm = str_to_json(componentConfig['json']);
                        saveData[componentConfig.id] = jsonForm['data'];
                        // console.log(saveData);
                        store.set(SAVE_NANE, saveData); //存储起来
                        update_data_sort();
                        $('#'+componentConfig.id).find('.hhq-comp-box').html(JSON.stringify(jsonForm['data']));
                        listen_action_click();
                    });
                },
                onEnd: function(evt) {
                    // console.log('onEnd.foo:', [evt.item, evt.from]);
                    update_data_sort();
                }
            });

            // 更新数据排序，2025.03.17
            function update_data_sort(){
                var newSaveData = {};//保存重新排序的结果
                $('#design-main').find('.component').each(function() {
                    var $dom = $(this);
                    var id = $dom.find('.component-item').attr('id');
                    // var componentKey = $dom.data('key');
                    // console.log(id);
                    newSaveData[id] = saveData[id];
                });
                saveData = newSaveData;
                store.set(SAVE_NANE, saveData); //存储起来
            }
        }

    });
</script>